package com.zmn.oms.admin.controller.work.list;

import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.data.LayuiTableDO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.office.excel.ExportExcelBuilder;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.business.interfaces.work.masterwork.MasterWorkBService;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.common.vo.TabQueryVO;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.services.interfaces.work.financework.FinanceWorkService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkOperatePermissionBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryExportBService;
import com.zmn.pay.common.constant.PayConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 类描述：一步维修工单列表controller
 *
 * @author lujia
 * @date 2019/8/12 18:04
 */
@Controller
@RequestMapping("/saas/work")
@Slf4j
public class SaasWorkListTabController extends WorkListTabBaseController {

    @Autowired
    FinanceWorkService financeWorkService;
    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderWorkListBService orderWorkListBService;
    @Autowired
    ZsOrderWorkBService zsOrderWorkBService;
    @Autowired
    ZsOrderWorkQueryBService zsOrderWorkQueryBService;
    @Autowired
    ZsOrderWorkOperatePermissionBService orderWorkOperatePermissionBService;
    @Autowired
    MasterWorkBService masterWorkBService;
    @Autowired
    OrderLogBService orderLogBService;
    @Autowired
    ZsOrderWorkQueryExportBService zsOrderWorkQueryExportBService;

    /**
     * 工单列表
     */
//    @RequiresPermissions("/saas/work/list.action")
    @RequestMapping(value = "/list")
    public ModelAndView list(OrderWorkQuery query, ModelAndView mv, String queryView) {
        mv.setViewName("work/list/saas/list");

        // 默认显示查询条件
        if (Objects.isNull(queryView)) {
            queryView = OmsPageConsts.QUERY_TAB_PRECISION_VIEW_NAME;
        }
        mv.addObject("hideQueryView", GlobalConsts.NO);

        // 默认日期
        if (Objects.equals(OmsPageConsts.QUERY_TAB_WAIT_DUTY_VIEW_NAME, queryView)) {
            // 默认30天
            mv.addObject("startTime", DateUtil.toString(DateUtil.addDays(DateUtil.getNow(), -30), "yyyy-MM-dd 00:00:00"));
            mv.addObject("endTime", DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd 23:59:59"));
        } else {
            mv.addObject("startTime", DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd 00:00:00"));
            mv.addObject("endTime", DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd 23:59:59"));
        }
        super.setDayLimit(mv);
        super.setDefaultModelAndView(mv);

        // tab
        List<TabQueryVO> tabList = Lists.newArrayList();

        // 精准查询
        if (StaffAdminService.isPermitted(OrderPremissionConsts.getPrecisionPermitUrl(OrderPremissionConsts.PATH_SAAS))) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_PRECISION).tabTypeName(OmsPageConsts.QUERY_TAB_PRECISION_NAME)
                    .queryView(OmsPageConsts.QUERY_TAB_PRECISION_VIEW_NAME).autoQuery(GlobalConsts.NO).build());
        }
        // 待确认
        if (StaffAdminService.isPermitted(OrderPremissionConsts.getWaitConfirmPermitUrl(OrderPremissionConsts.PATH_SAAS))) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_WAIT_CONFIRM).tabTypeName(OmsPageConsts.QUERY_TAB_WAIT_CONFIRM_NAME)
                    .queryView(OmsPageConsts.QUERY_TAB_WAIT_CONFIRM_VIEW_NAME)
                    .build());
        }
        // 待转单
        if (StaffAdminService.isPermitted(OrderPremissionConsts.getWaitTurnPermitUrl(OrderPremissionConsts.PATH_SAAS))) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_WAIT_TURN).tabTypeName(OmsPageConsts.QUERY_TAB_WAIT_TURN_NAME)
                    .queryView(OmsPageConsts.QUERY_TAB_WAIT_TURN_VIEW_NAME)
                    .build());
        }
        // 待分单
        if (StaffAdminService.isPermitted(OrderPremissionConsts.getWaitAssignPermitUrl(OrderPremissionConsts.PATH_SAAS))) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_WAIT_ASSIGN).tabTypeName(OmsPageConsts.QUERY_TAB_WAIT_ASSIGN_NAME).build());
        }
        // 待预约
        if (StaffAdminService.isPermitted(OrderPremissionConsts.getWaitDutyTimePermitUrl(OrderPremissionConsts.PATH_SAAS))) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_WAIT_DUTY).tabTypeName(OmsPageConsts.QUERY_TAB_WAIT_DUTY_NAME)
                    .queryView(OmsPageConsts.QUERY_TAB_WAIT_DUTY_VIEW_NAME).autoQuery(GlobalConsts.NO).build());
        }
        // 待派单
        if (StaffAdminService.isPermitted(OrderPremissionConsts.getWaitDistributePermitUrl(OrderPremissionConsts.PATH_SAAS))) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_WAIT_DISTRIBUTE).tabTypeName(OmsPageConsts.QUERY_TAB_WAIT_DISTRIBUTE_NAME)
                    .queryView(OmsPageConsts.QUERY_TAB_WAIT_DISTRIBUTE_VIEW_NAME).autoQuery(GlobalConsts.NO).build());
        }
        // 待领单
        if (StaffAdminService.isPermitted(OrderPremissionConsts.getWaitTakePermitUrl(OrderPremissionConsts.PATH_SAAS))) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_WAIT_TAKE).tabTypeName(OmsPageConsts.QUERY_TAB_WAIT_TAKE_NAME).build());
        }
        // 待收单
        if (StaffAdminService.isPermitted(OrderPremissionConsts.getWaitCheckoutPermitUrl(OrderPremissionConsts.PATH_SAAS))) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_WAIT_CHECKOUT).tabTypeName(OmsPageConsts.QUERY_TAB_WAIT_CHECKOUT_NAME).build());
        }
        // 待退款
        if (StaffAdminService.isPermitted(OrderPremissionConsts.getWaitRefundPermitUrl(OrderPremissionConsts.PATH_SAAS))) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_WAIT_REFUND).tabTypeName(OmsPageConsts.QUERY_TAB_WAIT_REFUND_NAME).build());
        }
        // 待算账
        if (StaffAdminService.isPermitted(OrderPremissionConsts.getWaitAccountPermitUrl(OrderPremissionConsts.PATH_SAAS))) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_WAIT_ACCOUNT).tabTypeName(OmsPageConsts.QUERY_TAB_WAIT_ACCOUNT_NAME).build());
        }
        // 取消缘由
        if (StaffAdminService.isPermitted(OrderPremissionConsts.getWaitCancelReasonPermitUrl(OrderPremissionConsts.PATH_SAAS))) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_CANCEL).tabTypeName(OmsPageConsts.QUERY_TAB_CANCEL_NAME)
                    .queryView(OmsPageConsts.QUERY_TAB_CANCEL_VIEW_NAME).autoQuery(GlobalConsts.NO).build());
        }

        mv.addObject("tabList", tabList);
        mv.addObject("queryView", queryView);

        // 默认查询条件
        mv.addObject("query", query);
        return mv;
    }

    /**
     * 工单列表 ajax
     */
    @RequiresPermissions("/saas/work/list.action")
    @PostMapping(value = "/ajax/list")
    @ResponseBody
    public ResultDTO ajaxList(@RequestBody OrderWorkQuery query) {
        // 处理查询条件
        processSearchQuery(query);

        if (!NumberUtil.isNullOrZero(query.getSourceCompanyId())) {
            List<KVDict<Integer>> shopList = super.getShopList(null, null, query.getSourceCompanyId(), null);
            if (!CollectionUtils.isEmpty(shopList)) {
                query.setShopIdList(shopList.stream().map(KVDict<Integer>::getValue).collect(Collectors.toList()));
            } else {
                query.setShopIdList(Lists.newArrayList(0));
            }
        }

        // 处理 tab 查询
        processTagTypeQuery(query);

        List<ZsOrderWorkVO> voList = zsOrderWorkQueryBService.listPageOrderWorkByQuery(query);
        LayuiTableDO<ZsOrderWorkVO> layuiTableDO = new LayuiTableDO<>();
        layuiTableDO.setCount(query.getTotalCount());
        layuiTableDO.setData(voList);
        return ResultDTO.success(layuiTableDO);
    }

    /**
     * 工单,单条 ajax
     */
    @RequiresPermissions("/saas/work/list.action")
    @GetMapping(value = "/ajax/row")
    @ResponseBody
    public ResultDTO ajaxRow(@Valid OrderWorkQuery query) {
        // 处理查询条件
        processSearchQuery(query);

        if (!NumberUtil.isNullOrZero(query.getSourceCompanyId())) {
            List<KVDict<Integer>> shopList = super.getShopList(null, null, query.getSourceCompanyId(), null);
            if (!CollectionUtils.isEmpty(shopList)) {
                query.setShopIdList(shopList.stream().map(KVDict<Integer>::getValue).collect(Collectors.toList()));
            } else {
                query.setShopIdList(Lists.newArrayList(0));
            }
        }

        List<ZsOrderWorkVO> voList = zsOrderWorkQueryBService.listPageOrderWorkByQueryNoRecord(query);
        if (CollectionUtils.isEmpty(voList)) {
            return null;
        }

        return ResultDTO.success(voList.get(0));
    }

    /**
     * 工单列表导出 ajax
     */
    @ResponseBody
    @RequestMapping(value = "/list/export")
    public void ajaxListExport(OrderWorkQuery query, HttpServletResponse response) throws Exception {

        query.setPageSize(10000);

        // 处理查询条件
        processSearchQuery(query);

        // 处理 tab 查询
        processTagTypeQuery(query);

        // 处理导出数量
        processExportPermitQuery(query);

        if (!NumberUtil.isNullOrZero(query.getSourceCompanyId())) {
            List<KVDict<Integer>> shopList = super.getShopList(null, null, query.getSourceCompanyId(), null);
            if (!CollectionUtils.isEmpty(shopList)) {
                query.setShopIdList(shopList.stream().map(KVDict<Integer>::getValue).collect(Collectors.toList()));
            } else {
                query.setShopIdList(Lists.newArrayList(0));
            }
        }

        // 导出
        ExportExcelBuilder excelBuilder = zsOrderWorkQueryExportBService.exportListOrderWorkByQuery(query, true);
        excelBuilder.exportExcel(response, "工单管理");
    }

    /**
     * 工单列表导出 ajax
     */
    @ResponseBody
    @PostMapping("/list/export/async")
    public ResultDTO ajaxListExportAsync(@RequestBody OrderWorkQuery query) {

        query.setPageSize(10000);

        // 处理查询条件
        processSearchQuery(query);

        // 处理 tab 查询
        processTagTypeQuery(query);

        // 处理导出数量
        processExportPermitQuery(query);

        if (!NumberUtil.isNullOrZero(query.getSourceCompanyId())) {
            List<KVDict<Integer>> shopList = super.getShopList(null, null, query.getSourceCompanyId(), null);
            if (!CollectionUtils.isEmpty(shopList)) {
                query.setShopIdList(shopList.stream().map(KVDict<Integer>::getValue).collect(Collectors.toList()));
            } else {
                query.setShopIdList(Lists.newArrayList(0));
            }
        }

        // 导出
        try {
            zsOrderWorkQueryExportBService.buildExportTask(query, true);
        } catch (OmsBaseException e) {
            return ResultDTO.fail(e.getMessage());
        }
        return ResultDTO.success();
    }

    /**
     * 处理查询条件
     *
     * @param query
     */
    private void processSearchQuery(OrderWorkQuery query) {
        // 脱敏
        // query.setIsSensitiveAddr(!StaffAdminService.isPermitted(OrderPremissionConsts.getOrderWorkListAddressPermitUrl(OrderPremissionConsts.MODULE_ID_SAAS)));
        query.setIsSensitiveAddr(true);
        query.setIsSensitiveTel(true);

        // 查询警告标识
        query.setQueryWarning(GlobalConsts.YES);

        // 查询服务平台是啄木鸟的
        query.setPlatWork(GlobalConsts.PLAT_MARK_SAAS);

        // 查询手机号对应的用户
        query.setQueryConcatPhoneUsers(true);
    }

}